package ie.wit.loanmanager;

import ie.wit.loanmanager.exceptions.TheLoanListIsEmptyException;
import ie.wit.loanmanager.exceptions.ThereIsNoLoanWithThisIdException;
import ie.wit.loanmanager.exceptions.UnknownItemException;
import ie.wit.loanmanager.gui.LoanManagerGui;
import ie.wit.loanmanager.model.Loan;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;


public class ControllerSystem {
	
	public static int lastId = 1;
	private List<Loan> loanList = new ArrayList<Loan>();
	private static ControllerSystem instance = null;
	
	
	protected ControllerSystem() {
	      // Exists only to defeat instantiation.
	}
	
	 public synchronized static ControllerSystem getInstance() {
	      if(instance == null) {
	         instance = new ControllerSystem();
	      }
	      return instance;
	 }
	
	
	public void addNewLoan(String name, String email, String phone, int yearReturn, int monthReturn, int dayReturn,
						   String loanDescription, String itemType) throws UnknownItemException {
		
		loanList.add(new Loan(name, email, phone,
							yearReturn, monthReturn, dayReturn,
							loanDescription, itemType, lastId));
		
		lastId++;
	}
	
	
	public void listAllLoan() {
		JOptionPane.showMessageDialog(null,loanList.toArray());
	}


	public void removeLoanById(int id) throws ThereIsNoLoanWithThisIdException, TheLoanListIsEmptyException {
		
		if (loanList.size() == 0)
			throw new TheLoanListIsEmptyException("There is no loan recorded in the system");
		
		for (Loan l : loanList) {
			if (l.getId() == id) {
				loanList.remove(l);
				return;
			}
		}
		
		throw new ThereIsNoLoanWithThisIdException("There is no loan with this id " + Integer.toString(id));
	}


	public LoanManagerGui getGui() {
		return new LoanManagerGui();
	}

	
	public void listLoanMe() {
		List<Loan> meLoan = new ArrayList<Loan>();
		
		for (Loan l : this.loanList) {
			if (l.getIsWith().equalsIgnoreCase("ME")) {
				meLoan.add(l);
			}
		}
		
		JOptionPane.showMessageDialog(null,meLoan.toArray());
		
	}

	
}
